package com.example.auth.demo.service;

import com.example.auth.demo.domain.PageResult;
import com.example.auth.demo.domain.auth.*;
import com.example.auth.demo.mapper.CustomerServiceMapper;
import com.example.auth.demo.service.CustomerServiceService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

@Service
public class CustomerServiceServiceImpl implements CustomerServiceService {

    @Resource
    private CustomerServiceMapper customerServiceMapper;

    // 工单表相关
    @Override
    public void createWorkOrder(WorkOrder workOrder) {
        customerServiceMapper.insertWorkOrder(workOrder);
    }

    @Override
    public WorkOrder getWorkOrderById(Long id) {
        return customerServiceMapper.getWorkOrderById(id);
    }

    @Override
    public PageResult<WorkOrder> getAllWorkOrdersByPage(int page, int pageSize) {
        int offset = (page - 1) * pageSize;
        List<WorkOrder> records = customerServiceMapper.getAllWorkOrdersByPage(pageSize, offset);
        int total = customerServiceMapper.getWorkOrderCount();

        return PageResult.<WorkOrder>builder()
                .page(page)
                .rows(pageSize)
                .total(total)
                .records(records)
                .build();
    }
    @Override
    public void updateWorkOrderStatus(WorkOrder workOrder) {
        customerServiceMapper.updateWorkOrderStatus(workOrder);
    }

    @Override
    public void deleteWorkOrder(Long id) {
        customerServiceMapper.deleteWorkOrder(id);
    }
    // 知识库表相关
    @Override
    public void createKnowledgeBase(KnowledgeBase knowledgeBase) {
        customerServiceMapper.insertKnowledgeBase(knowledgeBase);
    }

    @Override
    public KnowledgeBase getKnowledgeBaseById(Long id) {
        return customerServiceMapper.getKnowledgeBaseById(id);
    }

    @Override
    public PageResult<KnowledgeBase> getAllKnowledgeBases(int page, int pageSize, String sort, String order) {
        // 验证分页参数
        if (page <= 0) page = 1;
        if (pageSize <= 0 || pageSize > 100) pageSize = 10;

        // 验证排序字段（转为小写校验）
        List<String> validSorts = Arrays.asList("id", "category", "title", "create_time", "update_time");
        String normalizedSort = sort.toLowerCase();
        if (!validSorts.contains(normalizedSort)) {
            normalizedSort = "id";
        }

        // 验证排序方向（转为小写校验）
        String normalizedOrder = order.toLowerCase();
        if (!"asc".equals(normalizedOrder) && !"desc".equals(normalizedOrder)) {
            normalizedOrder = "desc";
        }

        // 计算偏移量（手动分页）
        int offset = (page - 1) * pageSize;

        // 构建排序SQL片段
        String orderBy = normalizedSort + " " + normalizedOrder;

        // 查询当前页数据
        List<KnowledgeBase> records = customerServiceMapper.getAllKnowledgeBasesByPage(offset, pageSize, orderBy);

        // 查询总记录数
        int total = customerServiceMapper.countAllKnowledgeBases();

        // 构建分页结果
        return PageResult.<KnowledgeBase>builder()
                .page(page)
                .rows(pageSize)
                .total(total)
                .records(records)
                .build();
    }
    @Override
    public void updateKnowledgeBase(KnowledgeBase knowledgeBase) {
        customerServiceMapper.updateKnowledgeBase(knowledgeBase);
    }

    @Override
    public void deleteKnowledgeBase(Long id) {
        customerServiceMapper.deleteKnowledgeBase(id);
    }

    // 玩家补偿表相关
    @Override
    public void createPlayerCompensation(PlayerCompensation playerCompensation) {
        // 设置创建时间
        playerCompensation.setCreateTime(new Date());
        customerServiceMapper.insertPlayerCompensation(playerCompensation);
    }

    @Override
    public List<PlayerCompensation> getPlayerCompensationsByPlayerId(Long playerId) {
        return customerServiceMapper.getPlayerCompensationsByPlayerId(playerId);
    }

    @Override
    public PageResult<PlayerCompensation> getAllPlayerCompensations(
            int page, int pageSize, Long playerId, String itemType, String sort, String order
    ) {
        // 参数校验（与之前相同）
        if (page <= 0) page = 1;
        if (pageSize <= 0 || pageSize > 100) pageSize = 10;

        // 严格校验排序字段（防止SQL注入）
        List<String> validSorts = Arrays.asList("id", "playerId", "itemType", "createTime");
        String normalizedSort = validSorts.contains(sort.toLowerCase()) ? sort : "createTime";

        // 严格校验排序方向
        String normalizedOrder = "asc".equalsIgnoreCase(order) ? "ASC" : "DESC";

        int offset = (page - 1) * pageSize;

        // 调用Mapper方法（直接传递参数）
        List<PlayerCompensation> records = customerServiceMapper.getAllPlayerCompensationsByPage(
                playerId, itemType, normalizedSort, normalizedOrder, offset, pageSize
        );

        int total = customerServiceMapper.countPlayerCompensations(playerId, itemType);

        return PageResult.<PlayerCompensation>builder()
                .page(page)
                .rows(pageSize)
                .total(total)
                .records(records)
                .build();
    }
    @Override
    public void updatePlayerCompensation(PlayerCompensation playerCompensation) {
        customerServiceMapper.updatePlayerCompensation(playerCompensation);
    }

    @Override
    public void deletePlayerCompensation(Long id) {
        customerServiceMapper.deletePlayerCompensation(id);
    }

    @Override
    public void banPlayer(PlayerBan playerBan) {
        // 设置封禁开始时间（当前时间）
        playerBan.setStartTime(new Date());
        customerServiceMapper.insertPlayerBan(playerBan);
    }

    @Override
    public PlayerBan getPlayerBanById(Long id) {
        return customerServiceMapper.getPlayerBanById(id);
    }

    @Override
    public List<PlayerBan> getPlayerBansByPlayerId(Long playerId) {
        return customerServiceMapper.getPlayerBansByPlayerId(playerId);
    }

    @Override
    public PageResult<PlayerBan> getAllPlayerBans(
            int page, int pageSize, Long playerId, String startTime, String endTime, String sort, String order
    ) {
        // 验证分页参数
        if (page <= 0) page = 1;
        if (pageSize <= 0 || pageSize > 100) pageSize = 10;

        // 验证排序字段
        List<String> validSorts = Arrays.asList("id", "playerId", "startTime", "endTime");
        String normalizedSort = sort.toLowerCase();
        if (!validSorts.contains(normalizedSort)) {
            normalizedSort = "startTime";
        }

        // 验证排序方向
        String normalizedOrder = order.toLowerCase();
        if (!"asc".equals(normalizedOrder) && !"desc".equals(normalizedOrder)) {
            normalizedOrder = "desc";
        }

        // 计算偏移量
        int offset = (page - 1) * pageSize;

        // 转换时间格式（支持ISO 8601和yyyy-MM-dd格式）
        DateTimeFormatter isoFormatter = DateTimeFormatter.ISO_DATE_TIME;
        DateTimeFormatter simpleFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        Date startDate = null;
        Date endDate = null;

        if (startTime != null && !startTime.isEmpty()) {
            try {
                // 尝试ISO格式
                LocalDateTime localDateTime = LocalDateTime.parse(startTime, isoFormatter);
                startDate = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
            } catch (DateTimeParseException e) {
                // 尝试简单格式
                try {
                    LocalDate localDate = LocalDate.parse(startTime, simpleFormatter);
                    startDate = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
                } catch (DateTimeParseException ex) {

                }
            }
        }

        if (endTime != null && !endTime.isEmpty()) {
            try {
                // 尝试ISO格式
                LocalDateTime localDateTime = LocalDateTime.parse(endTime, isoFormatter);
                endDate = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
            } catch (DateTimeParseException e) {
                // 尝试简单格式
                try {
                    LocalDate localDate = LocalDate.parse(endTime, simpleFormatter);
                    // 结束时间加1天，确保包含当天所有记录
                    endDate = Date.from(localDate.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant());
                } catch (DateTimeParseException ex) {

                }
            }
        }

        // 调用Mapper方法
        List<PlayerBan> records = customerServiceMapper.getAllPlayerBansByPage(
                playerId, startDate, endDate, normalizedSort, normalizedOrder, offset, pageSize
        );

        int total = customerServiceMapper.countPlayerBans(playerId, startDate, endDate);

        return PageResult.<PlayerBan>builder()
                .page(page)
                .rows(pageSize)
                .total(total)
                .records(records)
                .build();
    }

    @Override
    public void updatePlayerBan(PlayerBan playerBan) {
        customerServiceMapper.updatePlayerBan(playerBan);
    }

    @Override
    public void deletePlayerBan(Long id) {
        customerServiceMapper.deletePlayerBan(id);
    }
    // 角色及装备锁定表相关
    @Override
    public void lockRoleEquipment(RoleEquipmentLock roleEquipmentLock) {
        customerServiceMapper.insertRoleEquipmentLock(roleEquipmentLock);
    }

    @Override
    public RoleEquipmentLock getRoleEquipmentLockById(Long id) {
        return customerServiceMapper.getRoleEquipmentLockById(id);
    }

    @Override
    public List<RoleEquipmentLock> getRoleEquipmentLocksByRoleId(Long roleId) {
        return customerServiceMapper.getRoleEquipmentLocksByRoleId(roleId);
    }

    @Override
    public List<RoleEquipmentLock> getRoleEquipmentLocksByEquipmentId(Long equipmentId) {
        return customerServiceMapper.getRoleEquipmentLocksByEquipmentId(equipmentId);
    }
}